package com.useeinfo.oa.open.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.SelectVO;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.*;
import com.useeinfo.oa.modules.base.entity.*;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import com.useeinfo.oa.modules.threadUtil.ThreadUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

/**
 * @program: YiYouFuPlatform
 * @author: Taogq
 * @createDate: 2018-12-12
 * @createTime: 10:52:31
 */
@Controller
@RequestMapping("/web/admin/personnel")
public class PersonnelAdminManageAction {
    Logger logger = LoggerFactory.getLogger(PersonnelAdminManageAction.class);
    @Autowired
    private PersonnelBiz personnelBiz;
    @Autowired
    private OrganizationBiz organizationBiz;
    @Autowired
    private PositionBiz positionBiz;
    @Autowired
    private AreaBiz areaBiz;
    @Autowired
    SystemUserBiz systemUserBiz;

    private Workbook wb;
    private Sheet sheet;
    private Row row;

    /**
     * 普通用户列表跳转页面
     *
     * @return
     */
    @RequestMapping("/list")
    public ModelAndView list() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("pages/admin/personnel/list");
        return mv;
    }

    /**
     * 普通用户列表接口
     *
     * @param pageNo
     * @param pageSize
     * @param organizationId
     * @return
     */
    @RequestMapping("/listJson")
    @ResponseBody
    public JSONObject listJson(HttpServletRequest request, String pageNo, String pageSize, String organizationId, String name) {
        QueryParam queryParam = new QueryParam(pageNo, pageSize);
        if (StringConverters.null2Long(organizationId) > 0) {
            queryParam.getSqlMap().put("likeOrganizationId", organizationId);
        }
        if (!StringConverters.null2String(name).equals("")) {
            queryParam.getSqlMap().put("name", name);
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (null != enterprise) {
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId().toString());
        }
        return personnelBiz.findJSONList(queryParam);
    }


    /**
     * 跳转用户编辑页
     *
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("/editPage")
    public ModelAndView editPage(HttpServletRequest request, String id) {
        Personnel personnel = personnelBiz.findModel(StringConverters.null2Long(id));
        QueryParam queryParam = new QueryParam(-1, -1);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        List<Organization> organizationList = new ArrayList<>();
        List<Position> positionList = new ArrayList<>();
        List<Area> areaList = new ArrayList<>();
        if (null != enterprise) {
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId().toString());
            organizationList = organizationBiz.findList(queryParam);
            positionList = positionBiz.findList(queryParam);
            areaList = areaBiz.findList(queryParam);

        }
        ModelAndView mv = new ModelAndView();
        mv.addObject("personnel", null);
        if (null != personnel) {
            mv.addObject("personnel", personnel.toJSONObject());
        }
        JSONArray organization=new JSONArray();
        for(Organization o:organizationList){
            organization.add(o.toJSONObject());
        }
        mv.addObject("organizationList", organization);
        JSONArray position=new JSONArray();
        for(Position position1:positionList){
            position.add(position1.toJSONObject());
        }
        mv.addObject("positionList", position);
        mv.addObject("areaList", areaList);
        mv.setViewName("pages/admin/personnel/edit");
        return mv;
    }

    /**
     * 用户信息保存接口
     *
     * @param request
     * @param personnel
     * @param positionId
     * @param organizationId
     * @param areaIds
     * @param leader
     * @return
     */
    @RequestMapping("/addOrUpdate")
    @ResponseBody
    public ResultDto addOrUpdate(HttpServletRequest request, Personnel personnel, @RequestParam(value = "positionId[]", required = false) String[] positionId, @RequestParam(value = "organizationId[]", required = false) String[] organizationId, String areaIds, String leader) {

        try {
            return personnelBiz.saveUpdate(request, personnel, positionId, organizationId, areaIds, leader);
        } catch (Exception e) {
            logger.info(e.getMessage());
            e.getMessage();
            return ResultUtil.error();
        }

    }


    @RequestMapping("/designLeader")
    @ResponseBody
    public JSONObject designLeader(HttpServletRequest request, String userId, String flag) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        JSONObject jsonObject = new JSONObject();
        if (null == enterprise) {
            jsonObject.put("result", "false");
            jsonObject.put("message", "当前人员企业信息有误，请确认");
            return jsonObject;
        }
        return personnelBiz.designLeader(enterprise, userId, flag);

    }

    @RequestMapping("/delete")
    @ResponseBody
    public JSONObject delete(HttpServletRequest request, String userId) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        JSONObject jsonObject = new JSONObject();
        if (null == enterprise) {
            jsonObject.put("result", "false");
            jsonObject.put("message", "当前人员企业信息有误，请确认");
            return jsonObject;
        }
        return personnelBiz.deleteUser(enterprise, userId);

    }

    /**
     * 查询用户信息
     *
     * @param mobile
     * @return
     */
    @RequestMapping("/findUserByMobile")
    @ResponseBody
    public ResultDto findUserByMobile(HttpServletRequest request, String mobile) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (null == enterprise) {
            return ResultUtil.error("当前用户企业信息有误");
        }
        QueryParam queryParam = new QueryParam(-1, -1);
        queryParam.getSqlMap().put("mobile", mobile);

        List<Personnel> personnelList = new ArrayList<>();
        personnelList = personnelBiz.findList(queryParam);
        Personnel personnel = new Personnel();
        if (personnelList.size() > 0) {
            personnel = personnelList.get(0);
        } else {//判断当前用户不存在
            return ResultUtil.error();
        }
        queryParam.getSqlMap().put("enterpriseId", enterprise.getId().toString());
        personnelList = personnelBiz.findList(queryParam);
        if (personnelList.size() > 0) {
            personnel = personnelList.get(0);
        }else {
            personnel.setPositionSet(new HashSet<>());
            personnel.setPersonnnelOrganizationSet(new HashSet<>());
        }
        return ResultUtil.success(personnel.toJSONObject());

    }


    @RequestMapping("/importPage")
    public ModelAndView importPage(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        modelAndView.addObject("enterprise", enterprise);
        modelAndView.setViewName("pages/admin/personnel/personnelImport");

        return modelAndView;
    }


    @RequestMapping("/importUser")
    @ResponseBody
    public ResultDto importUser(HttpServletRequest request, MultipartFile file) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (null == enterprise) {
            return ResultUtil.error("当前用户企业信息有误，请退出重新登录");
        }
        if (null != file && !file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            String ext = fileName.substring(fileName.lastIndexOf("."));
            try {
                InputStream is = file.getInputStream();
                if (".xls".equals(ext)) {
                    wb = new HSSFWorkbook(is);
                } else if (".xlsx".equals(ext)) {
                    wb = new XSSFWorkbook(is);
                } else {
                    return ResultUtil.error("请导入正确格式的文件（Excel）");
                }
            } catch (Exception e) {
                logger.error("IOException", e);
                return ResultUtil.error("导入失败，请刷新后重试");
            }
        }
        ResultDto resultDto = checkData(enterprise);
        if (resultDto.getStatus() != 0) {
            return resultDto;
        }
        ThreadUtils.importUserThread(personnelBiz,wb,enterprise);
        return ResultUtil.success();
    }

    public ResultDto checkData(Enterprise enterprise) {
        if (wb == null) {
            return ResultUtil.error("Workbook对象为空！");
        }
        List moblies = new ArrayList();
        sheet = wb.getSheetAt(0);
        // 得到总行数
        int rowNum = sheet.getLastRowNum();
        row = sheet.getRow(0);
        int colNum = row.getPhysicalNumberOfCells();
        // 正文内容应该从第二行开始,第一行为表头的标题
        QueryParam queryParam = new QueryParam();
        JSONArray existUser = new JSONArray();
        JSONArray result = new JSONArray();
        JSONObject jsonObject;
        for (int i = 1; i <= rowNum; i++) {
            row = sheet.getRow(i);
            if ("".equals(StringConverters.null2String(getCellFormatValue(row.getCell(1))))) {
                jsonObject = new JSONObject();
                jsonObject.put("msg", "Excel数据第" + (i + 1) + "行，手机号数据存在问题，请确认后重新提交");
                result.add(jsonObject);
            }
            if (personnelBiz.checkMobile(StringConverters.null2String(getCellFormatValue(row.getCell(1))))) {//验证手机是否已存在--企业管理员或平台管理者
                jsonObject = new JSONObject();
                jsonObject.put("msg", "Excel数据第" + (i + 1) + "行，手机号数据存在问题（不可为空），该手机号已被企业管理者或平台管理者占用");
                result.add(jsonObject);
                // return ResultUtil.error("该手机号已被企业管理者或平台管理者占用");
            }
            if (moblies.contains(StringConverters.null2String(getCellFormatValue(row.getCell(1))))) {
                jsonObject = new JSONObject();
                jsonObject.put("msg", "Excel数据第" + (i + 1) + "行，手机号:" + StringConverters.null2String(getCellFormatValue(row.getCell(1))) + "数据存在问题,出现重复数据，请确认后重新提交");
                result.add(jsonObject);
            }
            moblies.add(StringConverters.null2String(getCellFormatValue(row.getCell(1))));

            //需求变更工号可以为空
//            if ("".equals(StringConverters.null2String(getCellFormatValue(row.getCell(2))))) {
//                jsonObject = new JSONObject();
//                jsonObject.put("msg", "Excel数据第" + (i + 1) + "行，工号数据存在问题（不可为空），请确认后重新提交");
//                result.add(jsonObject);
//            }

            if ("".equals(StringConverters.null2String(getCellFormatValue(row.getCell(5))))) {
                jsonObject = new JSONObject();
                jsonObject.put("msg", "Excel数据第" + (i + 1) + "行，岗位数据存在问题（不可为空），请确认后重新提交");
                result.add(jsonObject);
            } else {
                String postHql = "select obj from Position obj where obj.enterprise.id=" + enterprise.getId() + " and obj.name = '" + StringConverters.null2String(getCellFormatValue(row.getCell(5))) + "'";
                List<Position> positionList = positionBiz.hqlExcute(postHql);
                if (CollectionUtils.isEmpty(positionList)) {
                    jsonObject = new JSONObject();
                    jsonObject.put("msg", "Excel数据第" + (i + 1) + "行，" + StringConverters.null2String(getCellFormatValue(row.getCell(5))) + "岗位数据存在问题，在当前企业下不存在该岗位");
                    result.add(jsonObject);
                }
            }
            if ("".equals(StringConverters.null2String(getCellFormatValue(row.getCell(6))))) {
                jsonObject = new JSONObject();
                jsonObject.put("msg", "Excel数据第" + (i + 1) + "行，部门数据存在问题（不可为空），请确认后重新提交");
                result.add(jsonObject);
            } else {
                String orgHql = "select obj from Organization obj where obj.enterprise.id=" + enterprise.getId() + " and obj.organizationName = '" + StringConverters.null2String(getCellFormatValue(row.getCell(6))) + "'";
                List<Organization> organizationList = organizationBiz.hqlExcute(orgHql);
                if (CollectionUtils.isEmpty(organizationList)) {
                    jsonObject = new JSONObject();
                    jsonObject.put("msg", "Excel数据第" + (i + 1) + "行，" + StringConverters.null2String(getCellFormatValue(row.getCell(6))) + "部门数据存在问题，在当前企业下不存在该部门");
                    result.add(jsonObject);
                }
            }
            if ("".equals(StringConverters.null2String(getCellFormatValue(row.getCell(8))))) {
                jsonObject = new JSONObject();
                jsonObject.put("msg", "Excel数据第" + (i + 1) + "行，区域数据存在问题（不可为空），请确认后重新提交");
                result.add(jsonObject);
            }
            String[] areaNames = StringConverters.null2String(getCellFormatValue(row.getCell(8))).split("/");
            for (String areaName : areaNames) {
                if (!StringConverters.null2String(areaName).equals("")) {
                    String areaHql = "select obj from Area obj where obj.enterprise.id=" + enterprise.getId() + " and obj.areaName = '" + areaName + "'";
                    List<Area> areaList = areaBiz.hqlExcute(areaHql);
                    if (CollectionUtils.isEmpty(areaList)) {
                        jsonObject = new JSONObject();
                        jsonObject.put("msg", "Excel数据第" + (i + 1) + "行，区域：" + areaName + "数据存在问题，在当前企业下不存在该区域");
                        result.add(jsonObject);
                    }
                }
            }


        }
        if (result.size() > 0) {
            ResultDto resultDto = new ResultDto();
            resultDto.setStatus(1);
            resultDto.setData(result);
            return resultDto;
        }
        return ResultUtil.success();
    }

    /**
     * 根据Cell类型设置数据
     *
     * @param cell
     * @return
     * @author zengwendong
     */
    private Object getCellFormatValue(Cell cell) {
        Object cellvalue = "";
        if (cell != null) {
            // 判断当前Cell的Type
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC:// 如果当前Cell的Type为NUMERIC
                case Cell.CELL_TYPE_FORMULA: {
                    // 判断当前的cell是否为Date
                    if (DateUtil.isCellDateFormatted(cell)) {
                        // 如果是Date类型则，转化为Data格式
                        // data格式是带时分秒的：2013-7-10 0:00:00
                        // cellvalue = cell.getDateCellValue().toLocaleString();
                        // data格式是不带带时分秒的：2013-7-10
                        Date date = cell.getDateCellValue();
                        cellvalue = date;
                    } else {// 如果是纯数字

                        // 取得当前Cell的数值
                        DecimalFormat dfs = new DecimalFormat("0");

                        cellvalue = dfs.format(cell.getNumericCellValue());
                    }
                    break;
                }
                case Cell.CELL_TYPE_STRING:// 如果当前Cell的Type为STRING
                    // 取得当前的Cell字符串
                    cellvalue = cell.getRichStringCellValue().getString();
                    break;
                default:// 默认的Cell值
                    cellvalue = "";
            }
        } else {
            cellvalue = "";
        }
        return cellvalue;
    }



}
